<template>
  <div class="row">
    <div class="col-xs-6 col-md-3" v-for="item in items" :key="item.id">
      <div class="thumbnail">
        <img :src="require('../assets/'+item.img)">
        <div class="caption">
          <p class="price">￥{{item.price}}</p>
          <p>{{item.name}}</p>
          <p><a href="#" class="btn btn-primary" role="button" @click.prevent="addCart(item.id)">添加购物车</a></p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  export default {
    name: 'Phone',
    data() {
      return {
        items: []
      }
    },
    mounted() {
      this.getItems()
    },
    methods: {
      getItems() {
        const items = localStorage.getItem("items")
        this.items = JSON.parse(items);
      },
      addCart(id) {
        //根据商品ID查找商品
        let items = localStorage.getItem("items")
        items = JSON.parse(items);
        const item = items.find(val => val.id == id)
        //添加购物车
        let carts = localStorage.getItem("carts")
        carts = JSON.parse(carts)
        console.log(carts)
        console.log(item)
        carts.push(item)
        
        localStorage.setItem("carts", JSON.stringify(carts))
      }
    }
  }
</script>

<style scoped="scoped">
  .price {
    color: #e4393c;
    font-size: 20px;
  }
</style>
